package com.podmanager.UI;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.podmanager.data.*;

public class SubscriptionFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
	private ImageButton subscription_addButton;
//	private ImageCursorAdapter mAdapter;
	private ImageCursorAdapter mAdapter;
	private static final int SUBSCRIPTION_LOADER_ID = 100;
	
	public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 
 //       Bundle args = getArguments();
 
        View rootView = inflater.inflate(R.layout.subscription_layout, container, false);
		setupButtons(rootView);
		setupListAdapter();
        return rootView;
    }

	private void setupListAdapter() {		
		int[] viewIDs = new int[] { 
			R.id.subscription_item_episodes_downloaded, 
			R.id.subscription_item_new_episodes,
			R.id.subscription_item_title, 
			R.id.subscription_item_URL,
			R.id.subscription_item_image};
		String[] columns = new String[] {
			PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED, 
			PMDatabase.SUBSCRIPTIONS.EPISODE_COUNT,
			PMDatabase.SUBSCRIPTIONS.SUB_TITLE,
			PMDatabase.SUBSCRIPTIONS.URL_FEED,
			PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH};
		mAdapter = new ImageCursorAdapter(this.getActivity(),
				R.layout.subscription_item_layout, null, columns, viewIDs,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		setListAdapter(mAdapter);
		// Initialize the Loader with id LOADER_ID, and this activity.
		// As the Loader sees changes in the data, these changes will be
		// reported back to this activity through the LoaderCallbacks interface
		LoaderManager loaderManager = this.getLoaderManager();
		loaderManager.initLoader(SUBSCRIPTION_LOADER_ID, null, this);
		setListAdapter(mAdapter);
	}

	private void setupButtons(View view) {
	    subscription_addButton = (ImageButton) view.findViewById(R.id.subscription_add_button);
		subscription_addButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(v.getContext(), AddSubscription.class);
				startActivityForResult(i, 0);
			}});
	}
	
    @Override
    public void onListItemClick(ListView l, View v, int position, long list_RowID) {
    	Spinner filter = (Spinner)this.getActivity().findViewById(R.id.episodes_filter_dropdown);
    	filter.setSelection((int)list_RowID);    	
    	int count = filter.getCount();
    	for (int i = 0; i < count; i++) {
    	    Cursor value = (Cursor) filter.getItemAtPosition(i);
    	    long filter_RowID = value.getLong(value.getColumnIndex("_id"));
    	    if (filter_RowID == list_RowID) {
    	    	filter.setSelection(i);
    	    }
    	}
    	this.getActivity().getActionBar().setSelectedNavigationItem(PodManager.PageEnum.Episodes.ordinal());
    }
    

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		registerForContextMenu(getListView());
	}
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.menu_delete:
            	new DeleteSubscriptionAsyncTask(this.getActivity()).execute(""+info.id);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = this.getActivity().getMenuInflater();
        inflater.inflate(R.menu.subscription_context_menu, menu);
    }
    
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// We create the CursorLoader object here using the content URI. This
		// loader object will pull columns based on the PROJECTION.
		return new CursorLoader(this.getActivity(), DBContentProvider.SUBSCRIPTION_URI,
				PMDatabase.SUBSCRIPTIONS.COLUMN_NAMES, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.swapCursor(null);
	}
}
